#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
分别打包WMS Simple的各个组件
"""

import os
import sys
import subprocess
from pathlib import Path

# 项目根目录
project_root = Path(__file__).parent.parent
os.chdir(project_root)

def build_main_exe():
    """打包主程序"""
    print("========================================")
    print("打包主程序 (main_new.py)")
    print("========================================")
    
    cmd = [
        sys.executable, "-m", "PyInstaller",
        "--name=wms_simple",
        "--onedir",
        "--console",
        "--add-data=config.json:.",
        "--add-data=data:data",
        "--hidden-import=uvicorn.lifespan.on",
        "--hidden-import=uvicorn.lifespan.off", 
        "--hidden-import=uvicorn.protocols.websockets.auto",
        "--hidden-import=uvicorn.protocols.http.auto",
        "--hidden-import=uvicorn.protocols.websockets.websockets_impl",
        "--hidden-import=uvicorn.protocols.http.httptools_impl",
        "--hidden-import=uvicorn.protocols.http.h11_impl",
        "--hidden-import=uvicorn.logging",
        "--hidden-import=sqlalchemy.dialects.sqlite",
        "--hidden-import=win32timezone",
        "main_new.py"
    ]
    
    try:
        subprocess.run(cmd, check=True)
        print("✅ 主程序打包成功！")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ 主程序打包失败: {e}")
        return False

def build_service_config_exe():
    """打包服务配置管理工具"""
    print("========================================")
    print("打包服务配置管理工具 (service_config_manager.py)")
    print("========================================")
    
    cmd = [
        sys.executable, "-m", "PyInstaller",
        "--name=service_config_manager",
        "--onedir",
        "--windowed",  # GUI程序，不显示控制台
        "--add-data=config.json:.",
        "--hidden-import=win32serviceutil",
        "--hidden-import=win32service",
        "--hidden-import=win32event",
        "--hidden-import=servicemanager",
        "tools/service_config_manager.py"
    ]
    
    try:
        subprocess.run(cmd, check=True)
        print("✅ 服务配置管理工具打包成功！")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ 服务配置管理工具打包失败: {e}")
        return False

def build_service_exe():
    """打包Windows服务程序"""
    print("========================================")
    print("打包Windows服务程序 (wms_service.py)")
    print("========================================")
    
    cmd = [
        sys.executable, "-m", "PyInstaller",
        "--name=wms_service",
        "--onedir",
        "--console",
        "--add-data=config.json:.",
        "--add-data=data:data",
        "--hidden-import=uvicorn.lifespan.on",
        "--hidden-import=uvicorn.lifespan.off",
        "--hidden-import=uvicorn.protocols.websockets.auto",
        "--hidden-import=uvicorn.protocols.http.auto",
        "--hidden-import=uvicorn.protocols.websockets.websockets_impl",
        "--hidden-import=uvicorn.protocols.http.httptools_impl",
        "--hidden-import=uvicorn.protocols.http.h11_impl",
        "--hidden-import=uvicorn.logging",
        "--hidden-import=sqlalchemy.dialects.sqlite",
        "--hidden-import=win32timezone",
        "--hidden-import=win32serviceutil",
        "--hidden-import=win32service",
        "--hidden-import=win32event",
        "--hidden-import=servicemanager",
        "wms_service.py"
    ]
    
    try:
        subprocess.run(cmd, check=True)
        print("✅ Windows服务程序打包成功！")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ Windows服务程序打包失败: {e}")
        return False

def create_deployment_structure():
    """创建部署目录结构"""
    print("========================================")
    print("创建部署目录结构")
    print("========================================")
    
    deploy_dir = Path("deploy")
    if deploy_dir.exists():
        import shutil
        shutil.rmtree(deploy_dir)
    
    deploy_dir.mkdir()
    
    # 复制各个exe目录
    dist_dir = Path("dist")
    if (dist_dir / "wms_simple").exists():
        import shutil
        shutil.copytree(dist_dir / "wms_simple", deploy_dir / "wms_simple")
        print("✅ 复制主程序文件")
    
    if (dist_dir / "service_config_manager").exists():
        import shutil
        shutil.copytree(dist_dir / "service_config_manager", deploy_dir / "service_config_manager")
        print("✅ 复制服务配置管理工具")
    
    if (dist_dir / "wms_service").exists():
        import shutil
        shutil.copytree(dist_dir / "wms_service", deploy_dir / "wms_service")
        print("✅ 复制Windows服务程序")
    
    # 创建启动脚本
    create_batch_files(deploy_dir)
    
    # 创建说明文件
    create_readme(deploy_dir)
    
    print(f"✅ 部署目录创建完成: {deploy_dir}")

def create_batch_files(deploy_dir):
    """创建批处理文件"""
    # 主程序启动脚本
    main_bat = deploy_dir / "启动WMS系统.bat"
    with open(main_bat, 'w', encoding='gbk') as f:
        f.write('''@echo off
chcp 65001 > nul
echo ========================================
echo WMS Simple 料位管理系统
echo ========================================
echo 正在启动系统...
cd /d "%~dp0wms_simple"
wms_simple.exe
pause
''')
    
    # 服务管理工具启动脚本
    config_bat = deploy_dir / "服务管理工具.bat"
    with open(config_bat, 'w', encoding='gbk') as f:
        f.write('''@echo off
chcp 65001 > nul
echo ========================================
echo WMS Simple 服务管理工具
echo ========================================
echo 正在启动服务管理工具...
cd /d "%~dp0service_config_manager"
service_config_manager.exe
pause
''')
    
    # 服务安装脚本
    install_bat = deploy_dir / "安装Windows服务.bat"
    with open(install_bat, 'w', encoding='gbk') as f:
        f.write('''@echo off
chcp 65001 > nul
echo ========================================
echo 安装WMS Windows服务
echo ========================================
echo 需要管理员权限...
cd /d "%~dp0wms_service"
wms_service.exe install
if %errorlevel% == 0 (
    echo ✅ 服务安装成功！
    echo 正在启动服务...
    wms_service.exe start
    if %errorlevel% == 0 (
        echo ✅ 服务启动成功！
    ) else (
        echo ❌ 服务启动失败
    )
) else (
    echo ❌ 服务安装失败
)
pause
''')

def create_readme(deploy_dir):
    """创建说明文件"""
    readme = deploy_dir / "部署说明.txt"
    with open(readme, 'w', encoding='utf-8') as f:
        f.write('''WMS Simple 料位管理系统 - 部署说明

目录结构：
├── wms_simple/                    # 主程序目录
│   └── wms_simple.exe            # 主程序（GUI + API）
├── service_config_manager/        # 服务管理工具目录
│   └── service_config_manager.exe # 服务配置管理工具
├── wms_service/                   # Windows服务目录
│   └── wms_service.exe           # Windows服务程序
├── 启动WMS系统.bat               # 快速启动主程序
├── 服务管理工具.bat               # 快速启动服务管理工具
└── 安装Windows服务.bat           # 快速安装Windows服务

使用方式：

1. 开发/测试环境：
   - 双击"启动WMS系统.bat"
   - 会启动GUI界面和API服务器

2. 生产环境（推荐）：
   - 双击"服务管理工具.bat"打开服务管理界面
   - 点击"安装服务"按钮
   - 安装成功后点击"启动服务"
   - 服务会在后台运行，开机自启

3. 快速安装服务：
   - 右键"安装Windows服务.bat" → 以管理员身份运行
   - 会自动安装并启动Windows服务

注意事项：
- 首次安装服务需要管理员权限
- GUI模式和服务模式不能同时运行（端口冲突）
- 所有依赖已打包，无需安装Python环境
- 服务安装后会自动设置为开机自启动
''')

def main():
    """主函数"""
    print("========================================")
    print("WMS Simple 分别打包工具")
    print("========================================")
    print()
    
    success_count = 0
    
    # 打包主程序
    if build_main_exe():
        success_count += 1
    print()
    
    # 打包服务配置管理工具
    if build_service_config_exe():
        success_count += 1
    print()
    
    # 打包Windows服务程序
    if build_service_exe():
        success_count += 1
    print()
    
    # 创建部署结构
    if success_count > 0:
        create_deployment_structure()
        print()
        print("🎉 打包完成！")
        print(f"成功打包 {success_count}/3 个组件")
        print("部署包位置: deploy/")
    else:
        print("❌ 所有组件打包失败")

if __name__ == "__main__":
    main() 